package 二叉树;

import java.util.ArrayList;
import java.util.List;

public class LC_501二叉搜索树中的众数 {
    public static class TreeNode {
        int val;
        LC_501二叉搜索树中的众数.TreeNode left;
        LC_501二叉搜索树中的众数.TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, LC_501二叉搜索树中的众数.TreeNode left, LC_501二叉搜索树中的众数.TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    TreeNode pre=null;
    int count=0;
    int maxcount=0;
    List<Integer> result=new ArrayList<>();
    public int[] findMode(TreeNode root) {
        findMode1(root);
        int[] res=new int[result.size()];
        for(int i=0;i<result.size();i++){
            res[i]=result.get(i);
        }
        return res;
    }
    public  void findMode1(TreeNode root) {
        if(root==null) return ;
        //左
        findMode1(root.left);
        //中
        if(pre==null || pre.val!=root.val)
            count=1;
        else {
            count++;
        }
        if(count>maxcount){
            maxcount=count;
            result.clear();
            result.add(root.val);
        }
        else if(count==maxcount)
            result.add(root.val);
        pre=root;
        //右
        findMode1(root.right);
    }
//    public static void main(String[] args){
//        TreeNode root=new TreeNode('1');
//        TreeNode a=new TreeNode();
//        TreeNode b=new TreeNode('2');
//        TreeNode c=new TreeNode('2');
//        root.left=a;
//        root.right=b;
//        root.right.left=c;
//        findMode(root);
//    }
}
